package com.itheima.reggie.controller;
import com.itheima.reggie.UserService;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.common.SmsTemplate;
import com.itheima.reggie.domain.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;


@RestController
@Slf4j
public class UserController {

    @Autowired
    private HttpSession httpSession;

    @Autowired
    private SmsTemplate smsTemplate;

    @Autowired
    private UserService userService;
    //发送验证码
    @PostMapping("/user/sendMsg")
    public ResultInfo sen(@RequestBody Map<String ,String >map){
        //接收参数
        String phone = map.get("phone");
        //生成验证码
        //todo 写死，方便测试
        //String s = RandomUtil.randomNumbers(3);
        String s="123";
        log.info("生成的验证码是：{}",s);
        //保存到httpSession
        httpSession.setAttribute(phone, s);
        //发送验证码
        //smsTemplate.sendSms(phone, s);
        return ResultInfo.success(null);
    }
    //登录app
    @PostMapping("/user/login")
    public ResultInfo findMy(@RequestBody Map<String ,String >map){
        //接收参数
        String code = map.get("code");
        String phone = map.get("phone");
        //校验code
        String attribute = (String) httpSession.getAttribute(phone);
        if (!StringUtils.equals(code, attribute)
                ||StringUtils.isEmpty(code)
                ||StringUtils.isEmpty(attribute)) {
            return ResultInfo.error("对比失败");
        }
        //根据phone查询
       User user= userService.findAll(phone);
        if (user!=null){
            //数据库有 登录成功
        }else {
            //登录失败，去注册
            user = new User();
            user.setPhone(phone);
            user.setStatus(1);
            userService.save(user);
        }
        //放到数据库

        httpSession.setAttribute("SESSION_USER", user);
        //返回
        return ResultInfo.success(user);
    }
}